package com.yizisu.playerlibrary.view.video_view.view

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

import com.yizisu.playerlibrary.IYzsPlayer
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerConfig
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerHelper
import com.yizisu.playerlibrary.view.video_view.helper.SeekbarEvent
import com.yizisu.playerlibrary.view.video_view.helper.getCountTimeByLong

/**
 * 当前进度文本
 */
open class PlayerProgressText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(
    context,
    attrs,
    defStyleAttr
), IPlayerHelper {

    private var playerConfig: IPlayerConfig? = null
    private val seekbarListener
        get() = playerConfig?.seekBarEventData

    override fun onTick(playerModel: IYzsPlayer.Model) {
        super.onTick(playerModel)
        if (seekbarListener?.value?.isTouch != true) {
            text = playerModel.currentDurationText
        }
    }

    override fun onAttachPlayerConfig(playerConfig: IPlayerConfig) {
        super.onAttachPlayerConfig(playerConfig)
        this.playerConfig = playerConfig
        seekbarListener?.observeForever(::onSeekbarListener)
    }

    override fun onDetachedPlayerConfig(playerConfig: IPlayerConfig) {
        super.onDetachedPlayerConfig(playerConfig)
        seekbarListener?.removeObserver(::onSeekbarListener)
    }

    override fun isNeedPlayerListener(): Boolean {
        return true
    }

    private fun onSeekbarListener(data: SeekbarEvent?) {
        data?.progress?.let {
            text = getCountTimeByLong(it)
        }
    }
}